const fs = require("fs");
const path = require("path");
const util = require("util");
const url = require("url");
const http = require("http");
const https = require("https");
const router = require("express").Router();
const _ = require("lodash");
const FormData = require("form-data");
const multiparty = require("multiparty");
const randomstring = require("randomstring");
const Debug = require("debug");
const oauthmanage = require("./oauthmanage");
const axios = require("axios").default;

router.get("/login", (req, res) => {
    let stream = fs.createReadStream(path.join(__dirname, "login.html"));
    stream.pipe(res);
})

router.get("/v", (req, res, next) => {
    if (_.keys(req.query).length == 0) {
        let stream = fs.createReadStream(path.join(__dirname, "./yandex_auth.html"));
        stream.pipe(res);
        stream.on("error", (err) => {
            console.error(err);
        })
    } else {
        next();
    }
});

router.get("/v", (req, res) => {
    // let req_s = util.inspect(req);
    let req_s = {};
    req_s.path = req.path;
    req_s.url = req.url;
    req_s.originUrl = req.originalUrl;
    req_s.baseUrl = req.baseUrl;
    req_s.cookies = req.cookies;
    req_s.query = req.query;
    let access_token = req.query['access_token'];
    if (access_token) {
        //访问yandex验证
        axios.get("https://cloud-api.yandex.net/v1/disk", {
            headers: {
                Authorization: `OAuth ${access_token}`
            }
        }).then((axios_resp) => {
            let yandex_account = axios_resp.data['user']['login'];
            oauthmanage.setToken(access_token);

            axios.get(`https://cloud-api.yandex.net/v1/disk/resources/upload?path=${encodeURIComponent(`app:/upload.${randomstring.generate(5)}.html`)}`, {
                headers: {
                    Authorization: `OAuth ${access_token}`
                }
            }).then((axios_resp) => {
                let d = axios_resp.data;
                let href = d['href'];
                console.log("upload href is ", href);
                let parsedHref = url.parse(href);//https
                let streamFile = fs.createReadStream(
                    path.join(__dirname, "login.html"));

                let request = https.request({
                    method: d['method'],
                    hostname: parsedHref.hostname,
                    path: parsedHref.path,
                    search: parsedHref.search
                }, function (httpRes) {
                    console.log("have http response...");
                    httpRes.pipe(res);
                });
                streamFile.pipe(request);

            }).catch(axios_error => {
                res.send(500, util.inspect(axios_error));
            })
            // res.send(`access_token is ${access_token}user is ${yandex_account}`)
        }).catch(axios_error => {
            res.status(500);
            res.send(util.inspect(axios_error));
        })
        // res.cookie("id", "DEBUG");
        // res.redirect("/");
    } else {
        res.status(400);
        res.send("错误请求:请求中应该带有正确的查询字符串")
    }
});
router.get("/",(req,res)=>{
    res.redirect("./up");
});

router.get("/token",(req,res)=>{
    res.send(oauthmanage.getToken());
})

router.get("/up", (req, res) => {
    if (oauthmanage.getToken()) {
        res.render("uploadtest", {
            title: "Upload to Cloudnode and then to Yandex",
            uploadhref: "/uploadyandex/up"
        });
    } else {
        res.redirect("./login")
    }

});

/**
 * 妈的，不知道为什么贼慢？？？
 * 是multiparty的问题？还是/mnt文件夹的问题？（http-server下载的时候又蛮快的）
 * 还是前端的问题？
 * 居然好象是https的锅我操
 */
router.post("/up", (req, res) => {
    let mntpath = path.join(__dirname, "..", "..", "mnt");
    let form = new multiparty.Form({
        uploadDir: mntpath
    });
    form.parse(req, function (err, fileds, files) {
        if (err) {
            res.send(500, { err: err.message });
        } else {
            let file0 = files['file'][0];//这里的字符串‘file’对应表单里的name
            let fileOriginalName = file0['originalFilename'];
            let filePath = file0['path'];
            let access_token = oauthmanage.getToken();
            let dbg = Debug(fileOriginalName);
            dbg.enabled = true;
            dbg(`uploaded to /mnt`);
            axios.get(
                `https://cloud-api.yandex.net/v1/disk/resources/upload?path=${encodeURIComponent(`app:/${randomstring.generate(5)}.${fileOriginalName}`)}`,
                {
                    headers: {
                        Authorization: `OAuth ${access_token}`
                    }
                }).then((axios_resp) => {
                    let d = axios_resp.data;
                    let href = d['href'];
                    let parsedHref = url.parse(href);//https
                    let streamFile = fs.createReadStream(filePath);
                    let request = https.request({
                        method: d['method'],
                        hostname: parsedHref.hostname,
                        path: parsedHref.path,
                        search: parsedHref.search
                    }, function (httpRes) {
                        console.log("have http response...");
                        // httpRes.pipe(process.stdout);
                        dbg(`seems uploaded to Yandex`);
                        httpRes.on("data",(chunk)=>{
                            dbg(chunk.toString());
                        })
                    });
                    streamFile.pipe(request);
                    res.send(`${fileOriginalName},up to yandex...`)
                }).catch(axios_error => {
                    res.send(500, util.inspect(axios_error));
                })
        }
    })
});

router.post("/up/raw", (req, res) => {
    let mntpath = path.join(__dirname, "..", "..", "mnt");
    let filename = randomstring.generate("3") + ".fileupload";
    let fileStream = fs.createWriteStream(path.join(mntpath, filename));
    fileStream.on("close", () => {
        res.send("stream close!");
    });
    req.pipe(fileStream);
})
module.exports = router;